package top.xtcoder.jdcbase.base.service;

import java.math.BigDecimal;
import java.util.List;

import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.json.Json;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import top.xtcoder.jdcbase.base.core.KV;
import top.xtcoder.jdcbase.base.entity.system.SysConfigs;

@Service
public class ConfigService  {
	@Autowired
	private Dao dao;
	
	/**
	 * 获取配置信息
	 * @param fieldCode
	 * @return
	 */
	public SysConfigs getConfig(String fieldCode){
		SysConfigs config = dao.fetch(SysConfigs.class
				, Cnd.where("isdelete", "=", 0)
				.and("field_code", "=", fieldCode));
		return config;
	}
	public String getStrConfig(String fieldCode) {
		SysConfigs config = dao.fetch(SysConfigs.class
				, Cnd.where("isdelete", "=", 0)
				.and("field_code", "=", fieldCode));
		
		return config != null && config.getFieldType() == 1 ? config.getFieldValue() : "";
	}
	
	public NutMap getStrConfigs(String fieldCodes) {
		if(Strings.isBlank(fieldCodes)) {
			return null;
		}
		NutMap map = NutMap.NEW();
		String[] fieldCodeArr = fieldCodes.split(",");
		for(int i = 0; i < fieldCodeArr.length; i ++) {
			String str = getStrConfig(fieldCodeArr[i]);
			map.addv(fieldCodeArr[i], str);
		}
		return map;
	}
	
	public int getIntConfig(String fieldCode) {
		SysConfigs config = dao.fetch(SysConfigs.class
				, Cnd.where("isdelete", "=", 0)
				.and("field_code", "=", fieldCode));
		String v = config != null && config.getFieldType() == 1 ? config.getFieldValue() : "";
		if(Strings.isNotBlank(v)) {
			try {
				return Integer.parseInt(v);
			}catch(Exception e) {
				
			}
		}
		return 0;
	}
	
	public BigDecimal getBigDeciamlConfig(String fieldCode) {
		SysConfigs config = dao.fetch(SysConfigs.class
				, Cnd.where("isdelete", "=", 0)
				.and("field_code", "=", fieldCode));
		String v = config != null && config.getFieldType() == 1 ? config.getFieldValue() : "";
		if(Strings.isNotBlank(v)) {
			try {
				return new BigDecimal(v);
			}catch(Exception e) {
				
			}
		}
		return new BigDecimal(0);
	}
	
	public List<KV> getKvConfig(String fieldCode){
		SysConfigs config = dao.fetch(SysConfigs.class
				, Cnd.where("isdelete", "=", 0)
				.and("field_code", "=", fieldCode));
		if(config == null) return null;
		if(config.getFieldType() == 2 || config.getFieldType() == 3) {
			return Json.fromJsonAsList(KV.class, Json.toJson(config.getFieldValue()));
		}else {
			return null;
		}
	}
}
